package com.owulia.leetcode.string;

public class ReverseString {
    public void reverseString(char[] s) {
        int totalLength = s.length;
        int length = s.length / 2;
        for (int i = 0; i < length; i++) {
            int counterpoint = totalLength - i - 1;
            char temp = s[i];
            s[i] = s[counterpoint];
            s[counterpoint] = temp;
        }
    }


    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int index = 0;
        for (int i = 0; i < chars.length; i++) {
            if (Character.isSpaceChar(chars[i])) {
                int totalLength = i - index - 1;
                if (totalLength % 2 == 1) {
                    totalLength++;
                }
                int length = totalLength / 2;
                swap(chars, index, totalLength, length);
                index = i + 1;
            }
            if (!Character.isSpaceChar(chars[i]) && chars.length == i + 1) {
                int totalLength = i - index;
                int length = totalLength / 2;
                swap(chars, index, totalLength, length);
                index = i + 1;
            }
        }
        return new String(chars);
    }

    private static void swap(char[] chars, int index, int totalLength, int length) {
        for (int j = 0; j < length; j++) {
            int currentIndex = index + j;
            int counterpoint = index + totalLength - j;
            char temp = chars[currentIndex];
            chars[currentIndex] = chars[counterpoint];
            chars[counterpoint] = temp;
        }
    }

    public String reverseWordsV2(String s) {
        StringBuffer ret = new StringBuffer();
        int length = s.length();
        int i = 0;
        while (i < length) {
            int start = i;
            while (i < length && s.charAt(i) != ' ') {
                i++;
            }
            for (int p = start; p < i; p++) {
                ret.append(s.charAt(start + i - 1 - p));
            }
            while (i < length && s.charAt(i) == ' ') {
                i++;
                ret.append(' ');
            }
        }
        return ret.toString();
    }



    public static void main(String[] args) {
        String a = "Let's take LeetCode contest";
        System.out.println(reverseWords(a));
    }
}
